package com.prj.ufdm.cloud.ms.auth.bpo._impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.prj.ufdm.cloud.base.exception.BaseException;
import com.prj.ufdm.cloud.ms.auth.bpo.SysOrganBPO;
import com.prj.ufdm.cloud.ms.auth.dao.SysOrganDao;
import com.prj.ufdm.cloud.ms.auth.model.SysOrgan;
import com.prj.ufdm.cloud.ms.core.bpo._impl.BaseBPOImpl;

@Service(value = "sysOrganBPO")
public class SysOrganBPOImpl extends BaseBPOImpl<SysOrganDao,SysOrgan> implements SysOrganBPO {
	
	@Autowired
	private SysOrganDao sysOrganDao;

	
	@Override
	public Integer deleteOrganByOrganId(String id) throws Exception {
		return sysOrganDao.deleteOrganByOrganId(id);
	}

	@Override
	public List<SysOrgan> selectOrganListByOrganId(String id) throws Exception {
		return sysOrganDao.selectOrganListByOrganId(id);
	}


	@Override
	public SysOrgan selectByOrganId(String organId) throws Exception {
		return sysOrganDao.selectByOrganId(organId);
	}

	/**
	 * 用户id查询机构
	 */
	@Override
	public SysOrgan selectOrganByUserId(SysOrgan sysOrgan) throws Exception {
		if (StringUtils.isBlank(sysOrgan.getUserId())) {
			throw new BaseException("用户id为空，不能查询");
		}
		return sysOrganDao.selectOrganByUserId(sysOrgan);
	}


	@Override
	public int deleteChildrenOrganListByOrganId(SysOrgan sysOrgan) throws Exception {
		if(StringUtils.isBlank(sysOrgan.getId())) {
			throw new BaseException("机构id为空，不能删除！");
		}
		Set<String> set=new HashSet<String>();
		List<SysOrgan> sysFunctionList = sysOrganDao.selectChildrenListByOrganId(sysOrgan);
		//去空
		sysFunctionList.removeAll(Collections.singleton(null));
		int num=0;//递归次数控制，防止死循环(不包含循环查询次数)，如果想显示查询次数则，将num改为++num
		if(!CollectionUtils.isEmpty(sysFunctionList)) {
			for (int i=0;i<sysFunctionList.size();i++) {
				SysOrgan function = sysFunctionList.get(i);
				set.add(function.getId());
				num=getChildrenOrgan(function.getId(),set,++num);
			}
		}
		//包含自己
		set.add(sysOrgan.getId());
		List<String> sysOrganList=new ArrayList<String>();
		for (String organId : set) {
			//删除
			sysOrganList.add(organId);
		}
		if(!CollectionUtils.isEmpty(sysOrganList)) {
			sysOrganDao.deleteByIds(sysOrganList);
		}
		return 0;
	}
	
	
	//递归取出当前机构下，所有子机构
	@Override
	public int getChildrenOrgan(String parentId,Set<String> set,int num) throws Exception {
		if(num>10000) {
			//如果递归次数超过10000次，直接结束，防止死循环
			return num;
		}
		SysOrgan sysOrgan=new SysOrgan();
		sysOrgan.setId(parentId);
		List<SysOrgan> sysFunctionList = sysOrganDao.selectChildrenListByOrganId(sysOrgan);
		//去空
		sysFunctionList.removeAll(Collections.singleton(null));
		if(!CollectionUtils.isEmpty(sysFunctionList)) {
			for (int i=0;i<sysFunctionList.size();i++) {
				SysOrgan function = sysFunctionList.get(i);
				set.add(function.getId());
				num=getChildrenOrgan(function.getId(),set,++num);
			}
		}
		return num;		
	}

	/**
	 * 获取当前机构及所有上级机构
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<SysOrgan> getAllParentOrgan(String id) throws Exception{
		List<SysOrgan> list = new ArrayList<>();
		getAllParentOrgan(list,id);
		return list;
	}

	private void getAllParentOrgan(List<SysOrgan> list, String id) throws Exception{
		SysOrgan curOrgan = this.sysOrganDao.selectById(id);
		if(curOrgan==null)
			return ;
		list.add(0,curOrgan);
		if(curOrgan.getParentId()!=null)
			getAllParentOrgan(list, curOrgan.getParentId());
	}
	
	
	
	
    /**
     * Desc: 机构列表转为JSONObject 
     * @param listSysFunctionList
     * @return
     * @throws Exception
     * Date: 2020年1月14日
     * Author: Administrator
     */
    @Override
    public List<JSONObject> doExchangeSysOrganListToJson(List<SysOrgan> listSysOrgan) throws Exception {
		List<JSONObject> listParentSysFunctionJSONObject = new ArrayList<>();
		List<SysOrgan> parentSysOrganList = null;
		
		if(listSysOrgan!=null) {
			// 获取根节点
			parentSysOrganList = listSysOrgan.stream().filter( t -> t.getParentId().equals("0")).collect(Collectors.toList());
			// 添加每个根节点所有节点
			parentSysOrganList.stream().forEach(t -> {
				try {
					JSONObject treeObject = new JSONObject(true);
					treeObject.put("id", t.getId());
					treeObject.put("parentId", t.getParentId());
					treeObject.put("organCode", t.getOrganCode());
					treeObject.put("organName", t.getOrganName());
					treeObject.put("shortName", t.getShortName());
					treeObject.put("organType", t.getOrganType());
					treeObject.put("address", t.getAddress());
					treeObject.put("master", t.getMaster());
					treeObject.put("linkMan", t.getLinkMan());
					treeObject.put("linkpHone", t.getLinkPhone());
					treeObject.put("postCode", t.getPostCode());
					treeObject.put("status", t.getStatus());
					treeObject.put("remark", t.getRemark());
					treeObject.put("createUserId", t.getCreateUserId());
					treeObject.put("createUserName", t.getCreateUserName());
					treeObject.put("createTime", t.getCreateTime());
					treeObject.put("updateTime", t.getUpdateTime());
					treeObject.put("displayOrder", t.getDisplayOrder());
					treeObject.put("dependentAccount", t.getDependentAccount());
					treeObject.put("superName", t.getSuperName());
					treeObject.put("ownerFlag", t.getOwnerFlag());
					// 子节点（递归所有子节点）
					treeObject.put("children", getChildrenMenuJSONObject(listSysOrgan,t.getId()));
					listParentSysFunctionJSONObject.add(treeObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			});
		}
		return listParentSysFunctionJSONObject;
    }
    
    /**
     * Desc: 递归获取子节点
     * @param listSysFunctionList
     * @param parentId
     * @return
     * @throws Exception
     * Date: 2020年1月14日
     * Author: Administrator
     */
	private List<JSONObject> getChildrenMenuJSONObject(List<SysOrgan> listSysOrgan,String parentId) throws Exception  {
		List<JSONObject> listChildrenSysFunctionJSONObject = new ArrayList<>();
		List<SysOrgan> parentSysOrganList  = null;
		if(listSysOrgan!=null) {
			// 子节点列表
			parentSysOrganList = listSysOrgan.stream().filter( t -> t.getParentId().equals(parentId)).collect(Collectors.toList());
			// 遍历子节点
			if(parentSysOrganList!=null) {
				parentSysOrganList.stream().forEach(t -> {
					try {
						JSONObject treeObject = new JSONObject(true);
						treeObject.put("id", t.getId());
						treeObject.put("parentId", t.getParentId());
						treeObject.put("organCode", t.getOrganCode());
						treeObject.put("organName", t.getOrganName());
						treeObject.put("shortName", t.getShortName());
						treeObject.put("organType", t.getOrganType());
						treeObject.put("address", t.getAddress());
						treeObject.put("master", t.getMaster());
						treeObject.put("linkMan", t.getLinkMan());
						treeObject.put("linkpHone", t.getLinkPhone());
						treeObject.put("postCode", t.getPostCode());
						treeObject.put("status", t.getStatus());
						treeObject.put("remark", t.getRemark());
						treeObject.put("createUserId", t.getCreateUserId());
						treeObject.put("createUserName", t.getCreateUserName());
						treeObject.put("createTime", t.getCreateTime());
						treeObject.put("updateTime", t.getUpdateTime());
						treeObject.put("displayOrder", t.getDisplayOrder());
						treeObject.put("dependentAccount", t.getDependentAccount());
						treeObject.put("superName", t.getSuperName());
						treeObject.put("ownerFlag", t.getOwnerFlag());
						// 子节点（递归所有子节点）
						treeObject.put("children", getChildrenMenuJSONObject(listSysOrgan,t.getId()));
						listChildrenSysFunctionJSONObject.add(treeObject);
					} catch (Exception e) {
						e.printStackTrace();
					}
				});
			}
		}
		return listChildrenSysFunctionJSONObject;
	}

}
